const http = require('http');

const url = require('url');
const path = require('path');
const fs = require('fs');
const promisify = require('util').promisify;
const readFile = promisify(fs.readFile)
const querystring = require('querystring');
const template = require('art-template');


//数据库连接
require('./model/index.js');
//引入用户集合
const User =  require('./model/user.js')

//创建服务器
const app = http.createServer();
app.on('request', async (req, res) => {
    const method = req.method.toLowerCase();
    const pathname = url.parse(req.url, true).pathname;
    let realPath = path.join(__dirname, 'public', pathname);
    console.log(pathname);
    // console.log(fileType);
    if (method == 'get') {
        if (pathname == '/' || pathname == '/list') {
            if (pathname == '/') {
                listPath = realPath + 'list.html'
            }
            let users = await User.find()
            // console.log(users);
            let filePath = path.join(__dirname,'public','list.art')
            const htmls = template(filePath, {users});
            // console.log(htmls);
            res.end(htmls);
        } else if (pathname == '/add') {
            let listPath = realPath + '.html'
            async function getFile(filePath) {
                readFile(filePath, 'utf8')
                    .then((data) => {
                        res.end(data)
                    }, () => {
                        res.writeHead(404, {
                            'content-type': 'text/html;charset=utf8'
                        });
                        res.end("文件读取失败");
                    })
            }
            getFile(listPath);

            // let add = `
            //     <!DOCTYPE html>
            //     <html lang="en">

            //     <head>
            //         <meta charset="UTF-8">
            //         <meta http-equiv="X-UA-Compatible" content="IE=edge">
            //         <meta name="viewport" content="width=device-width, initial-scale=1.0">
            //         <title>Document</title>
            //         <link rel="stylesheet" href="./css/bootstrap.css">
            //     </head>

            //     <body>
            //         <div class="container">
            //             <div class="row">
            //                 <h2> 添加用户</h2>
            //             </div>
            //             <div class="row">
            //                 <form method="POST">
            //                     <div class="form-group">
            //                         <label for="exampleInputEmail1">用户名</label>
            //                         <input type="email" class="form-control" id="exampleInputEmail1" placeholder="请填写用户名">
            //                     </div>
            //                     <div class="form-group">
            //                         <label for="exampleInputPassword1">密码</label>
            //                         <input type="password" class="form-control" id="exampleInputPassword1" placeholder="请输入密码">
            //                     </div>
            //                     <div class="form-group">
            //                         <label for="exampleInputPassword1">年龄</label>
            //                         <input type="password" class="form-control" id="exampleInputPassword1" placeholder="请输入年龄">
            //                     </div>
            //                     <div class="form-group">
            //                         <label for="exampleInputPassword1">邮箱</label>
            //                         <input type="password" class="form-control" id="exampleInputPassword1" placeholder="请输入邮箱">
            //                     </div>
            //                     <div class="form-group">
            //                         <label for="exampleInputPassword1">请选择爱好</label>
            //                         <div class="checkbox">
            //                             <label><input type="checkbox"> 足球</label>
            //                             <label><input type="checkbox"> 蓝球</label>
            //                             <label><input type="checkbox"> 橄榄球</label>
            //                             <label><input type="checkbox"> 敲代码</label>
            //                             <label><input type="checkbox"> 抽烟</label>
            //                             <label><input type="checkbox"> 喝酒</label>
            //                             <label><input type="checkbox"> 烫头</label>

            //                         </div>
            //                     </div>
            //                     <button type="submit" class="btn btn-primary">添加用户</button>
            //                 </form>
            //             </div>
            //         </div>
            //     </body>

            //     </html>
            // `;
            // res.end(add);

        } else if (pathname == '/modify') {
            // console.log(url.parse(req.url, true).query);
            //获取要修改用户的id
            let userId = url.parse(req.url, true).query.id;           
            // console.log(userId);
            //根据id获取数据信息
            let userInfo = await User.findOne({ _id: userId });
            console.log(userInfo);
            let hobbies = ['橄榄球', '敲代码', '蓝球', '抽烟', '足球', '喝酒', '烫头'];
            let fromInfo = `
                <!DOCTYPE html>
                <html lang="en">
                
                <head>
                    <meta charset="UTF-8">
                    <meta http-equiv="X-UA-Compatible" content="IE=edge">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>修用户</title>
                    <link rel="stylesheet" href="./css/bootstrap.css">
                </head>
                
                <body>
                    <div class="container">
                        <div class="row">
                            <h2> 修改用户</h2>
                        </div>
                        <div class="row">
                            <form method="POST" action="/modify?id=${userInfo._id}">
                                <div class="form-group">
                                    <label for="exampleInputEmail1">用户名</label>
                                    <input name="name"  class="form-control" id="exampleInputEmail1" placeholder="请填写用户名" value="${userInfo.name}">
                                </div>
                                <div class="form-group">
                                    <label for="exampleInputPassword1">密码</label>
                                    <input name="password" value="${userInfo.password}"  class="form-control" id="exampleInputPassword1" placeholder="请输入密码">
                                </div>
                                <div class="form-group">
                                    <label for="exampleInputPassword1">年龄</label>
                                    <input name="age" value="${userInfo.age}"  class="form-control" id="exampleInputPassword1" placeholder="请输入年龄">
                                </div>
                                <div class="form-group">
                                    <label for="exampleInputPassword1">邮箱</label>
                                    <input name="email" value="${userInfo.email}" type="email" class="form-control" id="exampleInputPassword1" placeholder="请输入邮箱">
                                </div>
                                <div class="form-group">
                                    <label for="exampleInputPassword1">请选择爱好</label>
                                    <div class="checkbox">                                            
                                    
            `;
            hobbies.forEach(itme => {
                //判断当前循环项在不在用户的爱数组中
                let isHobby = userInfo.hobbies.includes(itme);
                console.log(isHobby);
                console.log(userInfo.hobbies);
                if (isHobby) {
                    fromInfo += `
                    <label><input type="checkbox" value="${itme}" name="hobbies" checked> ${itme}</label>   
                   `;
                } else {
                    fromInfo += `
                     <label><input type="checkbox" value="${itme}" name="hobbies" > ${itme}</label>   
                `;
                }
            })
            fromInfo += `
                            </div>
                            </div>
                            <button type="submit" class="btn btn-primary">提交</button>
                        </form>
                    </div>
                </div>
                </body>

                </html>
            `;
            res.end(fromInfo);
        } else if (pathname == '/delete') {
            //获取要修改用户的id
            const userId = url.parse(req.url, true).query.id;
            User.deleteOne({ _id: userId })
                .then(() => {
                    res.writeHead(200, {
                        'content-type': 'text/html;charset=utf8'
                    });
                    res.end("<Script>alert('删除成功！');location.href = '/list';</Script>");
                }, (error) => {
                    const err = error.errors;
                    // console.log(err);
                    let errInfo = [];
                    for (const key in err) {
                        errInfo.push(err[key]['properties']['message']);
                    }
                    console.log(errInfo);
                    res.writeHead(555, {
                        'content-type': 'text/html;charset=utf8'
                    });
                    let errInfoStr = JSON.stringify(errInfo);
                    let list = ` <Script>alert('${errInfoStr}');location.href = '/add';</Script>`;
                    res.end(list);
                })
        }
        else {
            readFile(realPath, 'utf8')
                .then((data) => {
                    res.end(data)
                }, () => {
                    res.writeHead(404, {
                        'content-type': 'text/html;charset=utf8'
                    });
                    res.end("文件读取失败");
                })
        }
    } else if (method == 'post') {
        if (pathname == '/add') {
            //接受用户提交的信息
            let formData = '';
            req.on('data', (params) => {
                formData += params; //读取请求体
            });
            req.on('end', () => {
                let qs = querystring.parse(formData);
                // console.log(qs);
                User.create(qs).then(() => {
                    //301代表重定向
                    //location 要跳转地址                  
                    // res.writeHead(301,{ 
                    //     Location:'/list'
                    // })
                    res.writeHead(200, {
                        'content-type': 'text/html;charset=utf8'
                    });
                    res.end("<Script>alert('添加成功！');location.href = '/list';</Script>");
                }, (error) => {
                    const err = error.errors;
                    // console.log(err);
                    let errInfo = [];
                    for (const key in err) {
                        errInfo.push(err[key]['properties']['message']);
                    }
                    console.log(errInfo);
                    res.writeHead(555, {
                        'content-type': 'text/html;charset=utf8'
                    });
                    let errInfoStr = JSON.stringify(errInfo);
                    let list = ` <Script>alert('${errInfoStr}');location.href = '/add';</Script>`;
                    res.end(list);
                })
            });
        } else if (pathname == '/modify') {
            //接受用户提交的信息
            let formData = '';
            req.on('data', (params) => {
                formData += params; //读取请求体
            });
            req.on('end', () => {
                let qs = querystring.parse(formData);
                console.log(qs);
                //获取要修改用户的id
                const userId = url.parse(req.url, true).query.id;
                User.updateOne({ _id: userId }, qs)
                    .then(() => {
                        res.writeHead(200, {
                            'content-type': 'text/html;charset=utf8'
                        });
                        res.end("<Script>alert('修改成功！');location.href = '/list';</Script>");
                    }, (error) => {
                        const err = error.errors;
                        // console.log(err);
                        let errInfo = [];
                        for (const key in err) {
                            errInfo.push(err[key]['properties']['message']);
                        }
                        console.log(errInfo);
                        res.writeHead(555, {
                            'content-type': 'text/html;charset=utf8'
                        });
                        let errInfoStr = JSON.stringify(errInfo);
                        let list = ` <Script>alert('${errInfoStr}');location.href = '/add';</Script>`;
                        res.end(list);
                    })
            });
        }
        else {
            res.end("55555")
        }

    } else {
        res.end('-_-');
    }
})
//监听8080端口
app.listen(8080, () => {
    console.log("服务器启动成功,请访问8080端口");
})



